package com.example.dllo.keepdemo.train.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.example.dllo.keepdemo.R;
import com.example.dllo.keepdemo.base.BaseActivity;
import com.example.dllo.keepdemo.tools.GsonRequest;
import com.example.dllo.keepdemo.tools.HeaderGridView;
import com.example.dllo.keepdemo.tools.MyListView;
import com.example.dllo.keepdemo.tools.RecyclerViewOnClick;
import com.example.dllo.keepdemo.tools.RoundImageView;
import com.example.dllo.keepdemo.tools.VolleySingleton;
import com.example.dllo.keepdemo.train.adapter.TrainWorkoutsListViewAdapter;
import com.example.dllo.keepdemo.train.adapter.TrainWorkoutsRecyclerViewAdapter;
import com.example.dllo.keepdemo.train.bean.TrainDynamicBean;
import com.example.dllo.keepdemo.train.bean.TrainWorkoutsBean;

import java.net.URL;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * Created by dllo on 16/1/14.
 */
public class TrainWorkoutsActivity extends BaseActivity implements View.OnClickListener, RecyclerViewOnClick, View.OnTouchListener {

    private MyListView myListView;
    private RelativeLayout relativeLayout;
    private RecyclerView recyclerView;
    private TrainWorkoutsRecyclerViewAdapter recyclerViewAdapter;
    private TrainWorkoutsListViewAdapter listViewAdapter;
    private ImageView imgDetail;
    private TrainWorkoutsBean trainWorkoutsBean;
    private TrainDynamicBean trainDynamicBean;
    private TextView tvTitle, tvSubtitle, tvDifficulty, tvFoundations, tvBody, tvTime, tvAction, tvEnergy, tvJoin, tvFinish, tvBackground;
    private RatingBar ratingBar;
    private RoundImageView roundImageView1,roundImageView2,roundImageView3,roundImageView4,roundImageView5,roundImageView6;
    private ImageView imgBackground;
    private Button btnBack, btnShare;
    private ScrollView scrollView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trainworkouts);
        btnBack = (Button) findViewById(R.id.btn_activity_trainworkouts_plan_back);
        btnShare = (Button) findViewById(R.id.btn_activity_trainworkouts_plan_share);
        myListView = (MyListView) findViewById(R.id.listview_activity_trainworkouts);
        relativeLayout = (RelativeLayout) findViewById(R.id.relative_activity_trainworkouts);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_activity_trainworkouts);
        imgDetail = (ImageView) findViewById(R.id.img_activity_trainworkouts_detail);
        tvTitle = (TextView) findViewById(R.id.tv_activity_trainworkouts_title);
        tvSubtitle = (TextView) findViewById(R.id.tv_activity_trainworkouts_subtitle);
        tvDifficulty = (TextView) findViewById(R.id.tv_activity_trainworkouts_difficulty);
        tvFoundations = (TextView) findViewById(R.id.tv_activity_trainworkouts_foundations);
        tvBody = (TextView) findViewById(R.id.tv_activity_trainworkouts_wholebody);
        tvTime = (TextView) findViewById(R.id.tv_activity_trainworkouts_time);
        tvAction = (TextView) findViewById(R.id.tv_activity_trainworkouts_action);
        tvEnergy = (TextView) findViewById(R.id.tv_activity_trainworkouts_energy);
        tvJoin = (TextView) findViewById(R.id.tv_activity_trainworkouts_joinnumber);
        ratingBar = (RatingBar) findViewById(R.id.rating_activity_trainworkouts_star);
        imgBackground = (ImageView) findViewById(R.id.img_activity_trainworkouts_backimg);
        tvBackground = (TextView) findViewById(R.id.tv_activity_trainworkouts_background);
        scrollView = (ScrollView) findViewById(R.id.scroll_activity_trainworkouts);


        btnBack.setOnClickListener(this);

        Intent intent = getIntent();
        String id = intent.getStringExtra("id");

        initRecyclerViewData(id);
        initListViewData(id);

        LinearLayout headerLinearLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.header_listview_activity_trainworkouts, null);
        RelativeLayout relativeLayoutHeader = (RelativeLayout) headerLinearLayout.findViewById(R.id.relative_header_activity_trainworkouts);
        tvFinish = (TextView) headerLinearLayout.findViewById(R.id.tv_header_activity_trainworkouts_finish_number);
        roundImageView1 = (RoundImageView) headerLinearLayout.findViewById(R.id.roundimg_header_activity_trainworkouts_head_one);
        roundImageView2 = (RoundImageView) headerLinearLayout.findViewById(R.id.roundimg_header_activity_trainworkouts_head_two);
        roundImageView3 = (RoundImageView) headerLinearLayout.findViewById(R.id.roundimg_header_activity_trainworkouts_head_three);
        roundImageView4 = (RoundImageView) headerLinearLayout.findViewById(R.id.roundimg_header_activity_trainworkouts_head_four);
        roundImageView5 = (RoundImageView) headerLinearLayout.findViewById(R.id.roundimg_header_activity_trainworkouts_head_five);
        roundImageView6 = (RoundImageView) headerLinearLayout.findViewById(R.id.roundimg_header_activity_trainworkouts_head_six);
        relativeLayoutHeader.setOnClickListener(this);
        myListView.addHeaderView(headerLinearLayout);
//        //去掉分割线
//        myListView.setDivider(null);

        scrollView.setOnTouchListener(this);

        imgDetail.setOnClickListener(this);
        relativeLayout.setOnClickListener(this);

    }

    public void headLoadData() {
        RoundImageView[] roundImageViews = {roundImageView1,roundImageView2,roundImageView3,roundImageView4,roundImageView5,roundImageView6};
        for (int i = 0; i < 6; i++) {
            if (trainDynamicBean.getData().get(i).getAuthor().getAvatar().equals("") ||!(trainDynamicBean.getData().get(i).getAuthor().getAvatar().endsWith(".jpg"))) {
                roundImageViews[i].setImageResource(R.mipmap.person_45_45);
            } else {
                ImageLoader.ImageListener listener = ImageLoader.getImageListener(roundImageViews[i],R.mipmap.person_45_45,R.mipmap.person_45_45);
                VolleySingleton.getImageLoader().get(trainDynamicBean.getData().get(i).getAuthor().getAvatar(),listener,50,50);
            }
        }
    }

    private void initListViewData(String id) {
        trainDynamicBean = new TrainDynamicBean();
        String url = "https://api.gotokeep.com/v1.1/workouts/" + id + "/timeline";
        GsonRequest<TrainDynamicBean> gsonRequest = new GsonRequest<TrainDynamicBean>(url, TrainDynamicBean.class, new Response.Listener<TrainDynamicBean>() {
            @Override
            public void onResponse(TrainDynamicBean response) {
                trainDynamicBean = response;
                listViewAdapter = new TrainWorkoutsListViewAdapter(TrainWorkoutsActivity.this, trainDynamicBean);
                myListView.setAdapter(listViewAdapter);
                headLoadData();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        VolleySingleton.getInstance()._addRequest(gsonRequest);
    }

    private void loadData() {
        tvTitle.setText(trainWorkoutsBean.getData().getName());
        tvSubtitle.setText(trainWorkoutsBean.getData().getDescription());
        tvDifficulty.setText("K" + trainWorkoutsBean.getData().getDifficulty());
        ratingBar.setRating((float) trainWorkoutsBean.getData().getDifficulty());
        tvBody.setText(trainWorkoutsBean.getData().getTrainingpoints().get(0).getName());
        tvTime.setText(trainWorkoutsBean.getData().getDuration() + "");
        tvAction.setText(trainWorkoutsBean.getData().getSteps().size() + "");
        tvEnergy.setText(trainWorkoutsBean.getData().getCalorie() + "");
        tvJoin.setText(trainWorkoutsBean.getData().getPioneer() + "人已参加");
        switch (trainWorkoutsBean.getData().getDifficulty()) {
            case 1:
                tvFoundations.setText("零基础");
                break;
            case 2:
                tvFoundations.setText("初学");
                break;
            case 3:
                tvFoundations.setText("进阶");
                break;
            case 4:
                tvFoundations.setText("强化");
                break;
            case 5:
                tvFoundations.setText("挑战");
                break;
        }
        ImageLoader.ImageListener listener = ImageLoader.getImageListener(imgBackground, R.mipmap.planmain320_370, R.mipmap.no_photo);
        VolleySingleton.getImageLoader().get(trainWorkoutsBean.getData().getPicture(), listener,400,200);

        tvFinish.setText(trainWorkoutsBean.getData().getTotalFinished() + "次完成");

    }

    private void initRecyclerViewData(String id) {
        trainWorkoutsBean = new TrainWorkoutsBean();

        String url = "https://api.gotokeep.com/v1.1/workouts/" + id;
        GsonRequest<TrainWorkoutsBean> gsonRequest = new GsonRequest<TrainWorkoutsBean>(url, TrainWorkoutsBean.class, new Response.Listener<TrainWorkoutsBean>() {
            @Override
            public void onResponse(TrainWorkoutsBean response) {
                trainWorkoutsBean = response;
                recyclerViewAdapter = new TrainWorkoutsRecyclerViewAdapter(TrainWorkoutsActivity.this, trainWorkoutsBean.getData().getSteps());
                recyclerView.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL));
                recyclerView.setAdapter(recyclerViewAdapter);
                recyclerViewAdapter.setOnClick(TrainWorkoutsActivity.this);
                loadData();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        VolleySingleton.getInstance()._addRequest(gsonRequest);

    }

    //menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_activity_trainplan, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_share_activity_trainplan:
                ShareSDK.initSDK(this);
                OnekeyShare oks = new OnekeyShare();
                //关闭sso授权
                oks.disableSSOWhenAuthorize();

                // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
                //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
                // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
                oks.setTitle(getString(R.string.share));
                // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
                oks.setTitleUrl("http://sharesdk.cn");
                // text是分享文本，所有平台都需要这个字段
                oks.setText("我是分享文本");
                // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
                oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
                // url仅在微信（包括好友和朋友圈）中使用
                oks.setUrl("http://sharesdk.cn");
                // comment是我对这条分享的评论，仅在人人网和QQ空间使用
                oks.setComment("我是测试评论文本");
                // site是分享此内容的网站名称，仅在QQ空间使用
                oks.setSite(getString(R.string.app_name));
                // siteUrl是分享此内容的网站地址，仅在QQ空间使用
                oks.setSiteUrl("http://sharesdk.cn");

                // 启动分享GUI
                oks.show(this);
                break;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.relative_activity_trainworkouts:
                toast("添加");
                break;
            case R.id.img_activity_trainworkouts_detail:
                Intent intent = new Intent(this, WorkoutsDetailActivity.class);
                intent.putExtra("detail", trainWorkoutsBean.getData().getDetail());
                startActivity(intent);
                break;
            case R.id.relative_header_activity_trainworkouts:
                Toast.makeText(this, "header", Toast.LENGTH_SHORT).show();
                Intent intent1 = new Intent(this, TrainDynamicActivity.class);
                intent1.putExtra("id",trainWorkoutsBean.getData().get_id());
                startActivity(intent1);
                break;
            case R.id.btn_activity_trainworkouts_plan_back:
                TrainWorkoutsActivity.this.finish();
                break;
            case R.id.btn_activity_trainworkouts_plan_share:
                Toast.makeText(this, "分享", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    //RecyclerView点击事件
    @Override
    public void OnClick(int position) {
        Toast.makeText(this, "position:" + position, Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(this, VideoActivity.class);
        intent.putExtra("title", trainWorkoutsBean.getData().getSteps().get(position).getExercise().getName());
        intent.putExtra("content", trainWorkoutsBean.getData().getSteps().get(position).getExercise().getDescription());
        intent.putExtra("video", trainWorkoutsBean.getData().getSteps().get(position).getExercise().getVideos().get(0).getUrl());
        startActivity(intent);
    }

    //ScrollView的滑动监听
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
                int scrollY = v.getScrollY();
                if (scrollY == 0) {
                    tvBackground.setAlpha(0);
                } else {
                    tvBackground.setAlpha(1);
                }
                break;
        }
        return false;
    }
}
